<template>
  <div class="main-container container-limited container-fluid page-holder">
    <div class="page-title-holder no-border-bottom">
      <h2 class="page-title">贡献信息</h2>
    </div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="uploads" ref="uploads" label="上传列表">
        <upload-docs :uploads.sync="form.uploads" @handleTags="saveTags" />
      </el-form-item>
      <el-form-item prop="folder" ref="folder" label="所属目录">
        <el-input v-show="false" v-model="form.folder" />
        <el-button
          size="small"
          v-text="form.folder || '选择目录'"
          @click="dialogVisible = true"
        />
        <select-folder-dialog
          :dialog-visible.sync="dialogVisible"
          :selected-folder-id.sync="form.folderId"
          :selected-folder-path.sync="form.folder"
          :space-id="Number(spaceId)"
        />
      </el-form-item>
      <el-form-item prop="title" ref="title" label="贡献标题">
        <el-input
          v-model="form.title"
          :placeholder="form.uploads.length ? '上传成功后自动生成贡献标题' : '请选择要上传的文件'"
          :disabled="!generated"
        />
      </el-form-item>
      <el-form-item label="贡献描述">
        <el-input v-model="form.desc" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">提交</el-button>
        <el-button class="float-right" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import UploadDocs from '@/views/documents/components/upload-docs';
import SelectFolderDialog from '@/components/shared/select-folder-dialog';

export default {
  name: 'upload-doc-confirm',
  components: { UploadDocs, SelectFolderDialog },
  data() {
    return {
      form: {
        folder: '',
        folderId: undefined,
        title: '',
        desc: '',
        uploads: [],
      },
      rules: {
        folder: [{ required: true, message: '请选择资源存放的目录' }],
        title: [{ required: true, validator: this.$va.contributionTitle }],
        uploads: [{ required: true, validator: this.$va.uploads, trigger: 'none' }],
      },
      tags: {}, // uid: tags
      loading: false,
      dialogVisible: false,
      generated: false,
    };
  },
  computed: {
    ...mapState({
      curFolder: 'currentFolder',
      curSpace: 'currentSpace',
    }),
    ...mapGetters(['isSpaceOwner', 'isSpaceAdmin']),
    spaceId() { return this.$route.params.spaceId; },
    createUploadsParams() {
      return {
        action: 'uploads',
        spaceId: this.spaceId,
        title: this.form.title.trim(),
        desc: this.form.desc.trim(),
        resources: this.form.uploads.map(file => ({
          class_type: 'ProductLocalFile',
          title: file.name,
          ext: `.${file.ext}`,
          parent_id: this.form.folderId === 0 ? undefined : this.form.folderId,
          ufile_key: file.response.key,
          ufile_size: file.size,
          tag_titles: this.tags[file.uid], // 上传文件的tag
        })),
      };
    },
    uploads() { return this.form.uploads; },
  },
  mounted() {
    this.initCurrentFolder();
  },
  destroyed() {
    this.setCurFolder();
  },
  methods: {
    ...mapActions({
      setCurFolder: 'setCurrentFolder',
    }),
    initCurrentFolder() {
      this.form.folder = this.curFolder.displayPath;
      this.form.folderId = this.curFolder.id;
    },
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.spaceContributions.create(this.createUploadsParams)
            .then((res) => {
              this.$root.$emit('loadSidebarItemsCount');
              this.$message.success('提交成功');
              this.setCurFolder();
              if (this.curSpace.autoAccept || this.isSpaceOwner || this.isSpaceAdmin) {
                const folderId = res.data.product_file_id;
                const url = `/spaces/${this.curSpace.id}/resources`;
                this.$router.push(`${url}${folderId ? `/${folderId}` : ''}`);
              } else this.$router.push(`/spaces/${this.curSpace.id}/contributions/${res.data.id}`);
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 保存标签
    saveTags(obj) { Object.assign(this.tags, obj); },
  },
  watch: {
    uploads(uploads) {
      if (!uploads.length) this.form.title = '';
      else if (uploads.map(file => file.status).every(status => status === 'success')) {
        let titles = '上传了';
        for (let i = 0; i < uploads.length; i += 1) {
          if (i !== 0) titles += '、';
          titles += `《${uploads[i].name}》`;
          if (i === 1) {
            titles += `${uploads.length > 2 ? '等' : ''}${uploads.length}个文件`;
            break;
          }
        }
        this.generated = true;
        this.form.title = titles;
      } else this.generated = false;
    },
  },
};
</script>

<style></style>
